package com.iss.umservice.manager.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import net.sf.json.util.NewBeanInstanceStrategy;

import org.apache.shiro.authc.credential.Md2CredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iss.iframework.common.errcode.AppRuntimeException;
import com.iss.iframework.util.DateUtil;
import com.iss.iframework.util.StringUtil;
import com.iss.iframework.util.security.MD5;
import com.iss.umservice.bean.AccountDisplayBean;
import com.iss.umservice.bean.AccountStationRefBean;
import com.iss.umservice.bean.AreaBean;
import com.iss.umservice.bean.CompanyBean;
import com.iss.umservice.bean.StationBean;
import com.iss.umservice.bean.SystemBean;
import com.iss.umservice.bean.UserAccount;
import com.iss.umservice.bean.UserInfo;
import com.iss.umservice.common.UMInfoType;
import com.iss.umservice.common.UMResourceType;
import com.iss.umservice.common.UMServiceErrorKey;
import com.iss.umservice.dao.AccountDao;
import com.iss.umservice.dao.SystemDao;
import com.iss.umservice.dao.UserDao;
import com.iss.umservice.manager.AccountManager;
import com.iss.umservice.manager.CompanyManager;
import com.iss.umservice.soa.impl.ChangePasswordResponse;
import com.sun.mail.iap.Response;

/**
 * 锟剿伙拷业锟斤拷锟竭硷拷锟斤拷锟斤拷
 * 
 * @author songzou
 * @date 2012-8-10
 */
@Service("accountManager")
public class AccountManagerImpl implements AccountManager
{
    private final Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private AccountDao accountDao;
    
    @Autowired
    private SystemDao systemDao;
    
    @Autowired
    private UserDao userDao;
    
    
    /**
     * {@inheritDoc}
     */
    public String serviceLogin(String userCode, String password)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("UserCode [{}] has post login request.", userCode);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(userCode))
        {
            logger.warn("Login Args is empty.");
            throw new AppRuntimeException(
                    UMServiceErrorKey.UM_LOGIN_USER_NOT_EXIST);
        }
        
        // 锟斤拷锟斤拷嘶锟絀D锟斤拷询锟剿伙拷锟斤拷息
        UserAccount userAccount = accountDao.queryUserAccountByUserCode(userCode.toLowerCase(Locale.ENGLISH));
        // 锟剿伙拷锟斤拷息锟角凤拷锟斤拷锟�
        if (userAccount == null)
        {
            logger.warn("Login userCode [{}] is not exist.", userCode);
            throw new AppRuntimeException(
                    UMServiceErrorKey.UM_LOGIN_USER_NOT_EXIST);
        }
        
        // 锟叫讹拷锟斤拷锟斤拷锟街凤拷锟角凤拷为锟斤拷
        if (StringUtil.isEmpty(password))
        {
            logger.warn("Login userCode [{}] password failed.", userCode);
            throw new AppRuntimeException(
                    UMServiceErrorKey.UM_LOGIN_PASSWORD_ERR);
        }
        
        // 锟饺较硷拷锟杰猴拷锟斤拷锟斤拷锟斤拷欠锟斤拷锟饺�
        String md5Password = new MD5().getMD5String(password);
        if (!userAccount.getAccountPassword().equalsIgnoreCase(md5Password))
        {
            logger.warn("Login userCode [{}] password failed.", userCode);
            throw new AppRuntimeException(
                    UMServiceErrorKey.UM_LOGIN_PASSWORD_ERR);
        }
        
        // 锟矫伙拷锟剿伙拷锟斤拷息状态
        UMInfoType accountState = UMInfoType.valueOf(userAccount.getAccountState());
        if (accountState == UMInfoType.DISABLE)
        {
            logger.warn("Login userCode [{}] state forbid.", userCode);
            throw new AppRuntimeException(
                    UMServiceErrorKey.UM_LOGIN_USER_FORBID);
        }
        
        // 锟斤拷询锟斤拷锟矫伙拷锟斤拷息锟斤拷锟�
        UserInfo userInfo = accountDao.queryUserInfoByUserAccountId(userAccount.getAccountId());
        if (userInfo == null)
        {
            logger.error("Login userCode [{}] failed, lost user info mapping.",
                    userCode);
            throw new AppRuntimeException(
                    UMServiceErrorKey.UM_LOGIN_USER_FORBID);
        }
        
        if (logger.isInfoEnabled())
        {
            logger.info("UserCode [{}] has login success.", userCode);
        }
        
        return userInfo.getUserId();
    }
    
    /**
     * {@inheritDoc}
     */
    public UserInfo queryUserInfoById(String userIdentifier)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Query UserInfo For UID [{}] request.", userIdentifier);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(userIdentifier))
        {
            logger.warn("Query UserInfo UID Args is empty.");
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId("0");
            userInfo.setUserName("锟睫达拷锟矫伙拷");
            return userInfo;
            //throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        UserInfo userInfo = accountDao.queryUserInfoById(userIdentifier);
        if (userInfo == null)
        {
            logger.error("Query UserInfo for UID [{}] failed, not found.",
                    userIdentifier);
            userInfo = new UserInfo();
            userInfo.setUserId("0");
            userInfo.setUserName("锟睫达拷锟矫伙拷");
        }
        
        if (logger.isInfoEnabled())
        {
            logger.info("Query UserInfo for UID [{}] success.", userIdentifier);
        }
        
        return userInfo;
    }
    
    /**
     * {@inheritDoc}
     */
    public String[] queryDataPerms(String userIdentifier, String systemSign)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Query DataPerms For UID [{}] SID [{}] request.",
                    userIdentifier,
                    systemSign);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(userIdentifier))
        {
            logger.warn("Query DataPerms UID Args is empty.");
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(systemSign))
        {
            logger.warn("Query DataPerms SID Args is empty.");
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_SYSTEM);
        }
        
        // 锟斤拷询锟斤拷锟斤拷系统锟斤拷息
        SystemBean systemBean = systemDao.querySystemInfoBySign(systemSign);
        if (systemBean == null)
        {
            logger.error("Query DataPerms SID [{}] failed, systeminfo not found.",
                    systemSign);
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_SYSTEM);
        }
        
        UserInfo userInfo = accountDao.queryUserInfoById(userIdentifier);
        if (userInfo == null)
        {
            logger.error("Query DataPerms for UID [{}] failed, user not found.",
                    userIdentifier);
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        // 锟斤拷询锟斤拷锟斤拷效锟斤拷锟斤拷源
        List<String> resourceIdList = accountDao.queryResourceValuesByCondition(userInfo.getAccountId(),
                systemBean.getSystemId(),
                UMResourceType.DATA_PERM);
        String[] resourceIds = resourceIdList.toArray(new String[0]);
        
        if (logger.isInfoEnabled())
        {
            Object[] args = new Object[] {userIdentifier, systemSign,
                    Arrays.toString(resourceIds)};
            logger.info("Query DataPerms For UID [{}] SID [{}] Success, Result={}",
                    args);
        }
        
        return resourceIds;
    }
    
    /**
     * {@inheritDoc}
     */
    public String[] queryMenuIds(String userIdentifier, String systemSign)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Query Menus For UID [{}] SID [{}] request.",
                    userIdentifier,
                    systemSign);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(userIdentifier))
        {
            logger.warn("Query Menus UID Args is empty.");
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(systemSign))
        {
            logger.warn("Query Menus SID Args is empty.");
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_SYSTEM);
        }
        
        // 锟斤拷询锟斤拷锟斤拷系统锟斤拷息
        SystemBean systemBean = systemDao.querySystemInfoBySign(systemSign);
        if (systemBean == null)
        {
            logger.error("Query Menus SID [{}] failed, systeminfo not found.",
                    systemSign);
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_SYSTEM);
        }
        
        UserInfo userInfo = accountDao.queryUserInfoById(userIdentifier);
        if (userInfo == null)
        {
            logger.error("Query Menus for UID [{}] failed, user not found.",
                    userIdentifier);
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        // 锟斤拷询锟斤拷锟斤拷效锟斤拷锟斤拷源
        List<String> menuIdList = accountDao.queryResourceValuesByCondition(userInfo.getAccountId(),
                systemBean.getSystemId(),
                UMResourceType.MENU);
        String[] menuIds = menuIdList.toArray(new String[0]);
        
        if (logger.isInfoEnabled())
        {
            Object[] args = new Object[] {userIdentifier, systemSign,
                    Arrays.toString(menuIds)};
            logger.info("Query Menus For UID [{}] SID [{}] Success, Result={}",
                    args);
        }
        
        return menuIds;
    }
    
    /**
     * {@inheritDoc}
     */
    public String[] queryOperPerms(String userIdentifier, String systemSign)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Query OperPerms For UID [{}] request.",
                    userIdentifier);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(userIdentifier))
        {
            logger.warn("Query OperPerms UID Args is empty.");
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(systemSign))
        {
            logger.warn("Query OperPerms SID Args is empty.");
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_SYSTEM);
        }
        
        // 锟斤拷询锟斤拷锟斤拷系统锟斤拷息
        SystemBean systemBean = systemDao.querySystemInfoBySign(systemSign);
        if (systemBean == null)
        {
            logger.error("Query OperPerms SID [{}] failed, systeminfo not found.",
                    systemSign);
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_SYSTEM);
        }
        
        UserInfo userInfo = accountDao.queryUserInfoById(userIdentifier);
        if (userInfo == null)
        {
            logger.error("Query OperPerms for UID [{}] failed, user not found.",
                    userIdentifier);
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        // 锟斤拷询锟斤拷锟斤拷效锟斤拷锟斤拷源
        List<String> resourceIdList = accountDao.queryResourceValuesByCondition(userInfo.getAccountId(),
                systemBean.getSystemId(),
                UMResourceType.OPER_PERM);
        String[] resourceIds = resourceIdList.toArray(new String[0]);
        
        if (logger.isInfoEnabled())
        {
            Object[] args = new Object[] {userIdentifier, systemSign,
                    Arrays.toString(resourceIds)};
            logger.info("Query OperPerms For UID [{}] SID [{}] Success, Result={}",
                    args);
        }
        
        return resourceIds;
    }
    
    /**
     * {@inheritDoc}
     */
    public String[] queryWorkFlowPerms(String userIdentifier)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Query WorkFlowPerms For UID [{}] request.",
                    userIdentifier);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(userIdentifier))
        {
            logger.warn("Query WorkFlowPerms UID Args is empty.");
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        UserInfo userInfo = accountDao.queryUserInfoById(userIdentifier);
        if (userInfo == null)
        {
            logger.error("Query WorkFlowPerms for UID [{}] failed, user not found.",
                    userIdentifier);
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        // 锟斤拷询锟斤拷锟斤拷效锟斤拷锟斤拷源
        List<String> resourceIdList = accountDao.queryResourceValuesByCondition(userInfo.getAccountId(),
                null,
                UMResourceType.WORKFLOW_PERM);
        String[] resourceIds = resourceIdList.toArray(new String[0]);
        
        if (logger.isInfoEnabled())
        {
            Object[] args = new Object[] {userIdentifier,
                    Arrays.toString(resourceIds)};
            logger.info("Query WorkFlowPerms For UID [{}] Success, Result={}",
                    args);
        }
        
        return resourceIds;
    }
    
    /**
     * {@inheritDoc}
     */
    public void addUserAccountInfo(UserAccount accountBean, UserInfo userBean)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Insert OperPerms For accountBean[{}]", accountBean);
        }
        
        // 锟斤拷锟斤拷锟斤拷锟組D5锟斤拷锟斤拷
        String accountPassword = new MD5().getMD5String(accountBean.getAccountPassword());
        
        // 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
        accountBean.setAccountPassword(accountPassword);
        //锟绞猴拷统一转锟斤拷小写
        if(StringUtil.isNotEmpty(accountBean.getAccountCode()))
        {
        accountBean.setAccountCode(accountBean.getAccountCode().toLowerCase(Locale.ENGLISH));
        }
        // 锟斤拷锟斤拷锟剿猴拷锟斤拷息
        accountDao.addUserAccountInfo(accountBean);
        
        List<AccountStationRefBean> beanList = new ArrayList<AccountStationRefBean>();
        
        if (null != accountBean.getStationId()
                && "" != accountBean.getStationId())
        {
            String[] stationId = accountBean.getStationId().split(",");
            
            // 锟斤拷锟紸ccountStationRefBean
            for (int i = 0; i < stationId.length; i++)
            {
                // 锟斤拷锟紸ccountStationRefBean
                AccountStationRefBean accountStationRefBean = new AccountStationRefBean();
                
                accountStationRefBean.setAccountId(accountBean.getAccountId());
                accountStationRefBean.setStationId(stationId[i]);
                
                beanList.add(accountStationRefBean);
            }
            
        }
        // 锟斤拷锟斤拷撕锟斤拷锟斤拷位锟侥讹拷应锟斤拷系
        accountDao.insertAccount_Station_Ref(beanList);
        // 锟斤拷锟斤拷没锟斤拷锟斤拷锟较�
        userBean.setAccountId(accountBean.getAccountId());
        
        // 锟斤拷锟斤拷菘锟斤拷锟斤拷seq
        int seq = userDao.queryUserIdSeq();
        
        // 锟斤拷锟�位
        String seqStr = StringUtil.prefixZoreFill(String.valueOf(seq % 100000000),
                8);
        
        // 锟斤拷锟斤拷没锟絀D
        String userId = "UI" + DateUtil.dateToStr(new Date(), "yyyyMMdd")
                + seqStr;
        
        userBean.setUserId(userId);
        
        userDao.addUserInfo(userBean);
    }
    
    /**
     * {@inheritDoc}
     */
    public List<UserAccount> queryUserAccountInfo(String accountCode, String companyName,int row,
            int offset) throws AppRuntimeException

    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Query OperPerms For accountCode[{}]", accountCode);
        }
        
        // 锟斤拷锟斤拷撕锟斤拷锟狡诧拷询锟剿猴拷
        if(StringUtil.isNotEmpty(accountCode))
        {
        accountCode=accountCode.toLowerCase(Locale.ENGLISH);
        }
        List<UserAccount> userAccounts = accountDao.queryUserAccountInfo(accountCode,companyName,
                row,
                offset);
        
        return userAccounts;
    }
    
    /**
     * {@inheritDoc}
     */
    public void insertAccount_Station_Ref(List<AccountStationRefBean> bean)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Insert OperPerms For AccountStationRefBean[{}]", bean);
        }
        
        accountDao.insertAccount_Station_Ref(bean);
    }
    
    /**
     * {@inheritDoc}
     */
    public int countAccountInfo(String accountCode,String companyName) throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Count OperPerms For accountCode[{}]", accountCode);
        }
        if(StringUtil.isNotEmpty(accountCode))
        {
        accountCode=accountCode.toLowerCase(Locale.ENGLISH);
        }
        int counts = accountDao.countAccountInfo(accountCode,companyName);
        
        return counts;
    }
    
    /**
     * {@inheritDoc}
     */
    public void delAccountInfoById(String accountId) throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Delete Account OperPerms For accountId[{}]",
                    accountId);
        }
        if (null != accountId && !"".equals(accountId))
        {
            String[] accountIds = accountId.split(",");
            
            for (int i = 0; i < accountIds.length; i++)
            {
                accountDao.delAccountInfoById(accountIds[i]); 
                UserInfo info = accountDao.queryUserInfoByUserAccountId(accountIds[i]);
                userDao.delUserInfoById(info.getUserId());
            }
        }
        
    }
    
    /**
     * {@inheritDoc}
     */
    public void modifyAccountInfo(UserAccount bean, UserInfo userBean)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Modify Account OperPerms For UserAccount[{}]", bean);
        }
        if(StringUtil.isNotEmpty(bean.getAccountCode()))
        {
        bean.setAccountCode(bean.getAccountCode().toLowerCase(Locale.ENGLISH));
        }
        accountDao.modifyAccountInfo(bean);
        
        List<AccountStationRefBean> beanList = new ArrayList<AccountStationRefBean>();
        
        if (null != bean.getStationId() && "" != bean.getStationId())
        {
            String[] stationId = bean.getStationId().split(",");
            
            // 锟斤拷锟紸ccountStationRefBean
            for (int i = 0; i < stationId.length; i++)
            {
                // 锟斤拷锟紸ccountStationRefBean
                AccountStationRefBean accountStationRefBean = new AccountStationRefBean();
                
                accountStationRefBean.setAccountId(bean.getAccountId());
                accountStationRefBean.setStationId(stationId[i]);
                
                beanList.add(accountStationRefBean);
            }
            
        }
        // 锟斤拷锟斤拷撕锟斤拷锟斤拷位锟侥讹拷应锟斤拷系
        accountDao.insertAccount_Station_Ref(beanList);
        
        // 锟睫革拷锟矫伙拷锟斤拷锟斤拷息
        userDao.modifyUserInfo(userBean);
    }
    
    /**
     * {@inheritDoc}
     */
    public UserAccount queryAccountInfoById(String accountId)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Modify Account OperPerms For accountId[{}]",
                    accountId);
        }
        
        UserAccount userAccount = accountDao.queryAccountInfoById(accountId);
        
        return userAccount;
    }
    
    /**
     * {@inheritDoc}
     */
    public List<AccountStationRefBean> queryAccount_Station_Ref(String accountCode)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Query Account_Station_Ref OperPerms For accountCode[{}]",
                    accountCode);
        }
        if(StringUtil.isNotEmpty(accountCode))
        {
        accountCode=accountCode.toLowerCase(Locale.ENGLISH);
        }
        List<AccountStationRefBean> bean = accountDao.queryAccount_Station_Ref(accountCode);
        
        return bean;
    }
    
    /**
     * 
     * {@inheritDoc}
     */
    public void modifyUAPasswordInfo(UserAccount accountBean)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Modify UserAccount Password OperPerms For accountBean[{}]",
                    accountBean);
        }
        if(StringUtil.isNotEmpty(accountBean.getAccountCode()))
        {
        accountBean.setAccountCode(accountBean.getAccountCode().toLowerCase(Locale.ENGLISH));
        }
        accountDao.modifyUAPasswordInfo(accountBean);
    }
    
    /**
     *{@inheritDoc}
     */
    public List<StationBean> queryStationInfoByAccountId(String accountId)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Query StationInfo  OperPerms For accountId[{}]",
                    accountId);
        }
        
        List<StationBean> beanList = accountDao.queryStationInfoByAccountId(accountId);
        
        return beanList;
    }
    
    /**
     *{@inheritDoc}
     */
    public List<AccountDisplayBean> getAccountDisplayBean(List<UserAccount> list)
            throws AppRuntimeException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("getAccountDisplayBean  OperPerms For list[{}]", list);
        }
        
        List<AccountDisplayBean> beaList = new ArrayList<AccountDisplayBean>();
        
        if (null != list && 0 != list.size())
        {
            for (int i = 0; i < list.size(); i++)
            {
                UserAccount account = (UserAccount)list.get(i);
                
                //锟斤拷取锟剿猴拷锟斤拷示锟斤拷Bean
                AccountDisplayBean displayBean = new AccountDisplayBean();
                
                //锟斤拷取锟斤拷位锟斤拷息
                List<StationBean> stationList = accountDao.queryStationInfoByAccountId(account.getAccountId());
                
                //锟斤拷取锟矫伙拷锟斤拷息
                UserInfo userInfo = accountDao.queryUserInfoByUserAccountId(account.getAccountId());
                
                //锟斤拷锟斤拷没锟絀D锟斤拷取锟斤拷锟斤拷锟斤拷息
                List<AreaBean> areaList = userDao.queryAreaInfoByUserId(userInfo.getUserId());
                
                //锟斤拷锟斤拷锟剿猴拷
                displayBean.setAccountId(account.getAccountId());
                
                //锟斤拷锟斤拷锟剿猴拷锟斤拷
                displayBean.setAccountName(account.getAccountCode());
                
                //锟斤拷锟斤拷锟剿猴拷状态
                displayBean.setAccountState(account.getAccountState());
                
                //锟斤拷锟斤拷锟矫伙拷锟斤拷锟�
                displayBean.setUserName(userInfo.getUserName());
                
                displayBean.setCompanyId(account.getCompanyId());
                
                displayBean.setCompanyName(account.getCompanyName());
                
                //锟斤拷锟矫革拷位锟斤拷息
                displayBean.setStationList(stationList);
                
                //锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷息
                displayBean.setAreaList(areaList);
                
                beaList.add(displayBean);
                
            }
        }
        return beaList;
    }

    public List<UserInfo> queryStationUserList(String stationId, String deptId)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Query queryStationUserList For stationId [{}] request.", stationId);
        }
        
        // 锟叫断匡拷值
        if (StringUtil.isEmpty(stationId))
        {
            logger.warn("Query queryStationUserList stationId Args is empty.");
            throw new AppRuntimeException(UMServiceErrorKey.UM_UNKNOW_USER);
        }
        
        List<UserInfo> userInfoList = accountDao.queryStationUserList(stationId,deptId);
        
        if (logger.isInfoEnabled())
        {
            logger.info("Query queryStationUserList for UID [{}] success.", stationId);
        }
        
        return userInfoList;
    }

    public String checkAccountCode(String accountCode)
    {
    	if(StringUtil.isNotEmpty(accountCode))
    	{
    	accountCode = accountCode.toLowerCase(Locale.ENGLISH);
    	}
    	return accountDao.checkAccountCode(accountCode);
    }

	public ChangePasswordResponse changePassword(String accountCode,
			String oldPassword, String newPassword) {
		ChangePasswordResponse response = new ChangePasswordResponse();
		if(StringUtil.isNotEmpty(accountCode))
		{
		accountCode = accountCode.toLowerCase(Locale.ENGLISH);
		}
		//锟斤拷锟斤拷锟绞号和撅拷锟斤拷锟斤拷锟角凤拷锟斤拷确
		UserAccount userAccount = accountDao.queryUserAccountByUserCode(accountCode);
        // 锟剿伙拷锟斤拷息锟角凤拷锟斤拷锟�
        if (userAccount == null)
        {
            logger.warn("Login userCode [{}] is not exist.", accountCode);
            response.setResponseCode(ChangePasswordResponse.FAILD_USER_NOTEXIST);
            response.setResponseMessage("this user is not exist,accountCode="+ accountCode);
            return response;
        }
        
        // 锟叫讹拷锟斤拷锟斤拷锟街凤拷锟角凤拷为锟斤拷
        if (StringUtil.isEmpty(oldPassword))
        {
            logger.warn("Login userCode [{}] password failed.", accountCode);
            response.setResponseCode(ChangePasswordResponse.FAILD_OLDPASSWORD_WRONG);
            response.setResponseMessage("oldPassword is empty,accountCode="+ accountCode);
            return response;
        }
        
        // 锟饺较硷拷锟杰猴拷锟斤拷锟斤拷锟斤拷欠锟斤拷锟饺�
        String md5Password = new MD5().getMD5String(oldPassword);
        if (!userAccount.getAccountPassword().equalsIgnoreCase(md5Password))
        {
            logger.warn("Login userCode [{}] password failed.", accountCode);
            response.setResponseCode(ChangePasswordResponse.FAILD_OLDPASSWORD_WRONG);
            response.setResponseMessage("oldPassword is wrong,accountCode="+ accountCode);
            return response;
        }
        
        //锟睫革拷锟斤拷锟斤拷
        String md5NewPassword = new MD5().getMD5String(newPassword);
       int resultCount =  accountDao.changePassword(accountCode,md5NewPassword);
       if(resultCount!=0)
       {
    	   response.setResponseCode(ChangePasswordResponse.SUCCESS);
    	   response.setResponseMessage("changePassword success!");
       }
       else 
       {
    	   response.setResponseCode(ChangePasswordResponse.FAILD_SYSTEM_ERROR);
    	   response.setResponseMessage("changePassword failed!");
       }
		return response;
	}



    public void resetAccountPass(String accountCode)
    {
        // TODO Auto-generated method stub
        String newPass="123456";
        newPass = new MD5().getMD5String(newPass);
        accountDao.changePassword(accountCode, newPass);
        
    }

    public UserAccount queryUserAccountByUserCode(String accountCode)
    {
        // TODO Auto-generated method stub
        
        return accountDao.queryUserAccountByUserCode(accountCode);
    }
    
    public String getAccountCode(String companyId,String companyName)
    {
        String accountCode = "comp"+companyId;
        //校锟斤拷accountCode锟角凤拷锟斤拷锟�
        UserAccount userAccount = accountDao.queryUserAccountByUserCode(accountCode);
        if(userAccount != null && userAccount.getAccountCode()!="")
        {
            accountCode+="_2";
        }
        return accountCode;        
    }

    public void createCompAccount(String companyId,String companyName)
    {
        UserAccount bean = new UserAccount();
        UserInfo userBean = new UserInfo();
        // TODO Auto-generated method stub
        //锟斤拷锟斤拷撕锟絀D
        String accountId = StringUtil.getPrimarySessionId();
        
        bean.setAccountId(accountId);
        
        //锟斤拷锟斤拷锟剿号的筹拷始状态
        bean.setAccountState(UMInfoType.ENABLE.toString());
        bean.setAccountCode(getAccountCode(companyId,companyName));
        bean.setAccountPassword("123456");
        bean.setCompanyId(companyId);
        userBean.setAccountCode(bean.getAccountCode());
        userBean.setAccountId(bean.getAccountId());
        userBean.setUserName(companyName);
        bean.setStationId(accountDao.getStationIdForComp());
        addUserAccountInfo(bean, userBean);
    }

	@Override
	public String queryUserType(String accountId) {
		// TODO Auto-generated method stub
		return accountDao.queryUserType(accountId);
	}
   
    
}
